package com.motu.vertx.module.utility.webtool;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class Aes {

//	// 密钥——AES算法要求密鈅128位(16字节)
//	public static byte[] getKey() throws Exception {
//		return "dc84aeeb15536c55".getBytes("UTF-8");
//	}
//	
//	public static byte[] getIv() throws Exception {
//		return "dc84aeeb15536c55".getBytes("UTF-8");
//	}
//
//	/***
//	 * aes加密
//	 * @param source 原文
//	 * @param keys 密钥
//	 * @return 密文
//	 */
//	public static byte[] encrypt(byte[] source, byte[] keys) throws GeneralSecurityException {
//		SecretKeySpec key = new SecretKeySpec(keys, "AES");
//		Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
//		cipher.init(Cipher.ENCRYPT_MODE, key);// 加密
//		return cipher.doFinal(source);
//	}
//
//	/***
//	 * aes解密
//	 * @param data 密文
//	 * @param keys 密钥
//	 * @return 原文
//	 */
//	public static byte[] decrypt(String data, byte[] keys, byte[] iv) throws Exception {
//		byte[] byteData = new BASE64Decoder().decodeBuffer(data);
////		System.out.println("_params_  byte = " + byteData + " size = " + byteData.length);
//		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
//        SecretKeySpec keyspec = new SecretKeySpec(keys, "AES");
//        IvParameterSpec ivspec = new IvParameterSpec(iv);
//        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);// 解密
//		return cipher.doFinal(byteData);
//	}
//	
//	public static byte[] encrypt(String value) {
//        byte[] encrypted = null;
//        try {
//
//            byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
//            Key skeySpec = new SecretKeySpec(raw, "AES");
//            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//            byte[] iv = new byte[cipher.getBlockSize()];
//
//            IvParameterSpec ivParams = new IvParameterSpec(iv);
//            cipher.init(Cipher.ENCRYPT_MODE, skeySpec,ivParams);
//            encrypted  = cipher.doFinal(value.getBytes());
//            System.out.println("encrypted string:" + encrypted.length);
//
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return encrypted;
//    }
//
//    public static  byte[]  decrypt(byte[] encrypted) {
//         byte[] original = null;
//         Cipher cipher = null;
//        try {
//            byte[] raw = new byte[]{'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};
//            Key key = new SecretKeySpec(raw, "AES");
//            cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
//            //the block size (in bytes), or 0 if the underlying algorithm is not a block cipher
//            byte[] ivByte = new byte[cipher.getBlockSize()];
//            //This class specifies an initialization vector (IV). Examples which use
//            //IVs are ciphers in feedback mode, e.g., DES in CBC mode and RSA ciphers with OAEP encoding operation.
//            IvParameterSpec ivParamsSpec = new IvParameterSpec(ivByte);
//            cipher.init(Cipher.DECRYPT_MODE, key, ivParamsSpec);
//            original= cipher.doFinal(encrypted);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
//        return original;
//    }  
    
    public static String key1 = "dwq4aeeb15536c55";
//	public static String key2 = "1234567890123456";
	
    public static byte[] aesEncrypt(byte[] source) throws GeneralSecurityException, UnsupportedEncodingException {
    	byte rawKeyData[] = key1.getBytes("UTF-8");
        // 处理密钥
        SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
        // 加密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(source);
    }
    public static byte[] aesDecrypt(byte[] data) throws GeneralSecurityException, UnsupportedEncodingException {
    	byte rawKeyData[] = key1.getBytes("UTF-8");
        // 处理密钥
        SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
        // 解密
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(data);
    }
    
//    public static void test()  {
//        // AES算法要求密鈅128位(16字节)
//        try {
////			byte rawKeyData1[] = key1.getBytes("UTF-8");
//			
////        byte[] source = "aabbccdd".getBytes();
//			String pwd = "YTAcpUFnn49P5VHr";
//			byte[] source=pwd.getBytes("UTF-8");
//			
//			// 加密
//			byte[] enc = aesEncrypt(source);
//			
//			String aespwd = parseByte2HexStr(enc);
//			System.out.println("aesEncrypt:" + source.length + "->" + enc.length +" aespwd : "+aespwd);
////			byte rawKeyData2[] = key2.getBytes("UTF-8");
//			byte bb[]  = parseHexStr2Byte(aespwd);
//			System.out.println("decrypt:" + bb.length);
//			// 解密
//			byte[] dec = aesDecrypt(bb);
//			
//			System.out.println("desDecrypt:" + enc.length + "->" + dec.length +" pwd :" +new String(dec,"UTF-8"));
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		} catch (GeneralSecurityException e) {
//			e.printStackTrace();
//		}
//        
////        ISFSObject obj1 = SFSObject.newFromBinaryData(dec);
////        System.out.println(obj1.toJson());
//        
//    }
//    
//    public static void test1() throws Exception {
//        // AES算法要求密鈅128位(16字节)
//        byte rawKeyData1[] = key1.getBytes("UTF-8");
//        
////        byte[] source = "aabbccdd".getBytes();
//        ISFSObject obj = new SFSObject();
//        obj.putInt("id", 1);
//        obj.putUtfString("name", "张三");
//        byte[] bytes = {1,1,1,1,1,1};
//        obj.putByteArray("b", bytes);
//        byte[] source=obj.toBinary();
//        
//        // 加密
//        byte[] enc = aesEncrypt(source);
//        System.out.println("aesEncrypt:" + source.length + "->" + enc.length);
//        
//        byte rawKeyData2[] = key2.getBytes("UTF-8");
//        
//        // 解密
//        byte[] dec = aesDecrypt(enc);
//        
//        System.out.println("desDecrypt:" + enc.length + "->" + dec.length);
//        
//        ISFSObject obj1 = SFSObject.newFromBinaryData(dec);
//        System.out.println(obj1.toJson());
//        
//    }
    
    /**将二进制转换成16进制 
     * @param buf 
     * @return 
     */  
    public static String parseByte2HexStr(byte buf[]) {  
            StringBuffer sb = new StringBuffer();  
            for (int i = 0; i < buf.length; i++) {  
                    String hex = Integer.toHexString(buf[i] & 0xFF);  
                    if (hex.length() == 1) {  
                            hex = '0' + hex;  
                    }  
                    sb.append(hex.toUpperCase());  
            }  
            return sb.toString();  
    }  
    
    /**将16进制转换为二进制 
     * @param hexStr 
     * @return 
     */  
    public static byte[] parseHexStr2Byte(String hexStr) {  
            if (hexStr.length() < 1)  
                    return null;  
            byte[] result = new byte[hexStr.length()/2];  
            for (int i = 0;i< hexStr.length()/2; i++) {  
                    int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);  
                    int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);  
                    result[i] = (byte) (high * 16 + low);  
            }  
            return result;  
    } 

    public static String getDecryptPwd(String str){
    	String pwd = "";
    	try {
			//						byte[] bbb = Aes.decrypt(obj.getString("shpwd"),Aes.getKey(), Aes.getIv());
			//						pwd = new String(bbb, "UTF-8");
			
//			System.out.println("shpwd = "+pwd);
			byte[] bbb = aesDecrypt(Aes.parseHexStr2Byte(str));
			pwd = new String(bbb, "UTF-8");
//			System.out.println("pwd = "+pwd);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return pwd;
    }
    public static String getEncodeString(String str) throws UnsupportedEncodingException, GeneralSecurityException{
    	return new String(aesEncrypt(str.getBytes("UTF-8")),"UTF-8");
    }
    
    
    /***
	 * aes加密
	 * @param source 原文
	 * @param keys 密钥
	 * @return 密文
     * @throws UnsupportedEncodingException 
	 */
	public static String encrypt(String str)  {
		try {
			byte keys[] = key1.getBytes("UTF-8");
			byte[] source = str.getBytes("UTF-8");
			SecretKeySpec key = new SecretKeySpec(keys, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 加密
			return new String(Base64.getEncoder().encode(cipher.doFinal(source)),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
	}

	/***
	 * aes解密
	 * @param data 密文
	 * @param keys 密钥
	 * @return 原文
	 * @throws UnsupportedEncodingException 
	 */
	public static String decrypt(String str)  {
		try {
			byte keys[] = key1.getBytes("UTF-8");
			byte[] data = Base64.getDecoder().decode(str.getBytes("UTF-8"));
			SecretKeySpec key = new SecretKeySpec(keys, "AES");
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, key);// 解密
			return new String(cipher.doFinal(data),"UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
	}
}
